/*eslint-disable*/
import React, { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import { easing } from 'maath';
import { useSnapshot } from 'valtio';
import state from '../store';

const CameraRig = ({children}) => {
  // 响应式更新颜色
  const group = useRef();
  const snap = useSnapshot(state);

  // 每一帧渲染时执行自定义逻辑
  useFrame((state, delta) => {
    // 适配窗口大小
    // 电脑端
    const isBreakpoint = window.innerWidth <= 1260;
    // 移动端
    const isMobile = window.innerWidth <= 600;

    // 设置初始模型位置
    let targetPosition = [-0.4, 0, 2];
    if(snap.intro) {
      if(isBreakpoint) targetPosition = [0, 0, 2];
      if(isMobile) targetPosition = [0, 0.2, 2.5];
    } else {
      if(isBreakpoint) targetPosition = [0, 0, 2];
      if(isMobile) targetPosition = [0, 0.2, 2.5];
    }

    // 设置相机位置
    easing.damp3(state.camera.position, targetPosition, 0.25, delta);

  // 转动相机使模型旋转
    easing.dampE(
      group.current.rotation,
      [state.pointer.y / 10, -state.pointer.x / 5, 0],
      0.25,
      delta
    );
  })
  
  return (
    <group ref={group}>
      {children}
    </group>
  )
}

export default CameraRig
